package weibo.acitivity;

import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.android.volley.VolleyError;
import com.xkh.xkh.MyApplication;
import com.xkh.xkh.R;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import java.util.ArrayList;
import java.util.List;

import inter.Delegate;
import inter.ResponseStatus;
import inter.SimpleInfo;
import managers.UIHandler;
import model.Blog;
import weibo.adapter.BokeAdapter;
import weibo.network.GetWeibo;
import weibo.network.GetWeiboClass;

/**
 * Created by Administrator on 2016/4/28.
 */
public class BokeActivity2 extends UIHandler.BaseActivity {


    PullToRefreshListView mPulltoRefreshListView;

    ListView lv_blog;

    TextView btn_send;

    //
    Button btn_selectedType;

    List<String> arrays = new ArrayList<String>();
    private int selectedPosion = 0;

    {
        arrays.add("全部");
    }

    // 微博
    List<Blog> blogs = new ArrayList<Blog>();

    BokeAdapter bokeAdapter = new BokeAdapter();

    {
        bokeAdapter.setBlogs(blogs);
    }


    // 获取最初的值
    Delegate getInitBoke = new Delegate() {
        @Override
        public void onResponse(String response) {
            if (!response.startsWith("{")) return;
            Gson gson = new Gson();
            GetWeibo.ResponseGetBlog responseGetBlog = gson.fromJson(response, GetWeibo.ResponseGetBlog.class);
            if (responseGetBlog.getStatus().equals(ResponseStatus.SUCCESS)) {
                List<weibo.dto.Blog> blogDatas = responseGetBlog.getBlogList();
                List<Blog> tmps = new ArrayList<Blog>();
                for (weibo.dto.Blog blogData : blogDatas) {
                    Blog blog = new Blog();
                    BlogData2Blog(blog, blogData);
                    tmps.add(blog);
                }
                blogs.clear();
                blogs.addAll(tmps);
                bokeAdapter.notifyDataSetChanged();
            }
        }

        @Override
        public void onErrorResponse(VolleyError error) {

        }
    };

    public void BlogData2Blog(Blog blog, weibo.dto.Blog blogData) {
        blog.setImage_Set(blogData.getImage_Set());
        blog.setBlog_ID(blogData.getBlog_ID());
        blog.setBlog_Text(blogData.getBlog_Text());
        blog.setBlog_Time(blogData.getBlog_Time());
        blog.setBlog_Type(blogData.getBlog_Type());
        blog.setImage_Num(blogData.getImage_Num());
        blog.setUser_Name(blogData.getUser_Name());
        blog.setBlog_class(blogData.getBlog_class());
    }

    // 获取最新博客
    Delegate getNewBoke = new Delegate() {
        @Override
        public void onResponse(String response) {
            mPulltoRefreshListView.onRefreshComplete();
            if (!response.startsWith("{")) return;
            Gson gson = new Gson();
            GetWeibo.ResponseGetBlog responseGetBlog = gson.fromJson(response, GetWeibo.ResponseGetBlog.class);
            if (responseGetBlog.getStatus().equals(ResponseStatus.SUCCESS)) {
                List<weibo.dto.Blog> blogDatas = responseGetBlog.getBlogList();
                List<Blog> tmps = new ArrayList<Blog>();
                for (weibo.dto.Blog blogData : blogDatas) {
                    Blog blog = new Blog();
                    BlogData2Blog(blog, blogData);
                    tmps.add(blog);
                }
                blogs.addAll(0, tmps);
                bokeAdapter.notifyDataSetChanged();
            }
        }

        @Override
        public void onErrorResponse(VolleyError error) {
            mPulltoRefreshListView.onRefreshComplete();
        }
    };

    // 获取以前的博客
    Delegate getOldBoke = new Delegate() {
        @Override
        public void onResponse(String response) {
            mPulltoRefreshListView.onRefreshComplete();
            if (!response.startsWith("{")) return;
            Gson gson = new Gson();
            GetWeibo.ResponseGetBlog responseGetBlog = gson.fromJson(response, GetWeibo.ResponseGetBlog.class);
            if (responseGetBlog.getStatus().equals(ResponseStatus.SUCCESS)) {
                List<weibo.dto.Blog> blogDatas = responseGetBlog.getBlogList();
                List<Blog> tmps = new ArrayList<Blog>();
                for (weibo.dto.Blog blogData : blogDatas) {
                    Blog blog = new Blog();
                    BlogData2Blog(blog, blogData);
                    tmps.add(blog);
                }

                blogs.addAll(tmps);
                bokeAdapter.notifyDataSetChanged();
            }
        }

        @Override
        public void onErrorResponse(VolleyError error) {
            mPulltoRefreshListView.onRefreshComplete();
        }
    };

    GetWeibo getWeiboInit = new GetWeibo();

    {
        getWeiboInit.setDelegate(getInitBoke);
    }

    GetWeibo getWeiboOld = new GetWeibo();

    {
        getWeiboOld.setDelegate(getOldBoke);
    }

    GetWeibo getWeiboNew = new GetWeibo();

    {
        getWeiboNew.setDelegate(getNewBoke);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_boke);
        initview();
//        initBlog(v);
        initdata();
    }


    private void initdata() {
        String type = MyApplication.aCache.getAsString(SimpleInfo.WEBlogType);
        if (type != null) {
            arrays = JSON.parseArray(type, String.class);
            arrays.add(0, "全部");
        } else {
            GetWeiboClass getWeiboClass = new GetWeiboClass();
            getWeiboClass.setDelegate(new Delegate() {
                @Override
                public void onResponse(String response) {
                    if (!response.startsWith("[")) return;
                    else {
                        arrays = JSON.parseArray(response, String.class);
                        arrays.add(0, "全部");
                        MyApplication.aCache.put(SimpleInfo.WEBlogType, response);
                    }
                }

                @Override
                public void onErrorResponse(VolleyError error) {

                }
            });
            getWeiboClass.get();
        }

        String weiboStr = MyApplication.aCache.getAsString(SimpleInfo.BOKE);
        if (weiboStr != null) {
            List<Blog> blogTmps = JSON.parseArray(weiboStr, Blog.class);
            blogs.addAll(blogTmps);
            bokeAdapter.notifyDataSetChanged();
        }
    }

    private void initBlog(View v) {
//        List<Blog> blogsTmp = SugarRecord.listAll(Blog.class);
//        blogs.addAll(blogsTmp);
//        bokeAdapter.notifyDataSetChanged();

        GetWeibo.RequestBlog requestBlog = new GetWeibo.RequestBlog();
        requestBlog.setIsNew("2");
        requestBlog.setClassName(classNameNow);
        getWeiboInit.setRequestBlog(requestBlog);
        getWeiboInit.get();


    }

    private void getNew() {
        GetWeibo.RequestBlog requestBlog = new GetWeibo.RequestBlog();
        requestBlog.setIsNew("1");
        if (blogs.isEmpty()) {
            mPulltoRefreshListView.onRefreshComplete();
            return;
        }
        requestBlog.setBlog_ID(blogs.get(0).getBlog_ID());
        requestBlog.setClassName(classNameNow);
        getWeiboNew.setRequestBlog(requestBlog);
        getWeiboNew.get();
    }

    private void getMore() {
        GetWeibo.RequestBlog requestBlog = new GetWeibo.RequestBlog();
        requestBlog.setIsNew("0");
        if (blogs.isEmpty()) {
            mPulltoRefreshListView.onRefreshComplete();
            return;
        }
        requestBlog.setBlog_ID(blogs.get(blogs.size() - 1).getBlog_ID());
        requestBlog.setClassName(classNameNow);
        getWeiboOld.setRequestBlog(requestBlog);
        getWeiboOld.get();
    }


    View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (v == btn_send) {
                Intent intent = new Intent(BokeActivity2.this, SendWeiboActivity.class);
                BokeActivity2.this.startActivity(intent);
            } else if (v == btn_selectedType) {
                showPopWindows();
            }
        }
    };

    private void showPopWindows() {
        View popupView = LayoutInflater.from(BokeActivity2.this).inflate(R.layout.popup, null);
        final PopupWindow popupWindow = new PopupWindow(popupView, ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT, true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        int popupWidth = popupView.getMeasuredWidth();
        int popupHeight = popupView.getMeasuredHeight();
        int[] location = new int[2];
        ListView lv_type = (ListView) popupView.findViewById(R.id.id_lv_types);


        BaseAdapter adapter = new ArrayAdapter<String>(BokeActivity2.this, R.layout.simple_text_item, arrays);
        lv_type.setAdapter(adapter);
        lv_type.setDividerHeight(4);
        adapter.notifyDataSetChanged();


        btn_selectedType.getLocationOnScreen(location);
        popupWindow.showAtLocation(btn_selectedType, Gravity.NO_GRAVITY, (location[0]),
                location[1] + btn_selectedType.getHeight());
        lv_type.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                popupWindow.dismiss();
                selected(i);

            }
        });
    }

    /**
     * 选择某一类
     *
     * @param i
     */

    private String classNameNow = "全部";

    private void selected(int i) {
        if (i == selectedPosion) return;
        selectedPosion = i;
        String className = arrays.get(i);
        classNameNow = className;
        btn_selectedType.setText(className);
        GetWeibo.RequestBlog requestBlog = new GetWeibo.RequestBlog();
        requestBlog.setIsNew("2");
        requestBlog.setClassName(className);
        getWeiboInit.setRequestBlog(requestBlog);
        getWeiboInit.get();


    }

    private void initview() {
        mPulltoRefreshListView = (PullToRefreshListView) findViewById(R.id.id_lv_boke);
        lv_blog = mPulltoRefreshListView.getRefreshableView();
        lv_blog.setAdapter(bokeAdapter);
        lv_blog.setDividerHeight((int) getResources().getDimension(R.dimen.y20));
        mPulltoRefreshListView.setMode(PullToRefreshBase.Mode.BOTH);
        mPulltoRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                Log.i("pull down", "下拉");
                getNew();

            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                getMore();
                Log.i("pull up", "上拉");

            }
        });
        btn_send = (TextView) findViewById(R.id.id_btn_send);
        btn_send.setOnClickListener(onClickListener);

        lv_blog.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Log.i("click", position + "");
                Blog blog = blogs.get(position - 1);
                Intent intent = new Intent(BokeActivity2.this, CommitActivity.class);
                intent.putExtra("blog", blog);
                BokeActivity2.this.startActivity(intent);
            }
        });

        btn_selectedType = (Button) findViewById(R.id.id_btn_selectType);
        btn_selectedType.setOnClickListener(onClickListener);
    }


    @Override
    public void onStart() {
        super.onStart();
        GetWeibo.RequestBlog requestBlog = new GetWeibo.RequestBlog();
        requestBlog.setIsNew("2");
        requestBlog.setClassName(classNameNow);
        GetWeibo getWeiboInit0 = new GetWeibo();
        getWeiboInit0.setRequestBlog(requestBlog);
        getWeiboInit0.setDelegate(new Delegate() {
            @Override
            public void onResponse(String response) {
                if (!response.startsWith("{")) return;
                Gson gson = new Gson();
                GetWeibo.ResponseGetBlog responseGetBlog = gson.fromJson(response, GetWeibo.ResponseGetBlog.class);
                if (responseGetBlog.getStatus().equals(ResponseStatus.SUCCESS)) {
                    List<weibo.dto.Blog> blogDatas = responseGetBlog.getBlogList();
                    List<Blog> tmps = new ArrayList<Blog>();
                    for (weibo.dto.Blog blogData : blogDatas) {
                        Blog blog = new Blog();
                        BlogData2Blog(blog, blogData);
                        tmps.add(blog);
                    }
                    blogs.clear();
                    blogs.addAll(tmps);
                    MyApplication.aCache.put(SimpleInfo.BOKE, JSON.toJSONString(blogs));
                    bokeAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        getWeiboInit0.get();
    }
}
